<template>
  <el-card shadow="hover">
    <!--        操作功能区-->
    <div>
      <a-form :model="queryParam" @keyup.enter="getUserList">
        <div class="flex gap-1">
            <a-form-item label="用户名称">
              <a-input
                placeholder="请输入用户名称"
                v-model:value="queryParam.username"
                style="width: 300px"
              />
            </a-form-item>
          <a-button type="primary" @click="getUserList()">
            <template #icon>
              <SearchOutlined />
            </template>
            搜索
          </a-button>
          <a-button type="primary" @click="searchReset()">
            <template #icon>
              <ReloadOutlined />
            </template>
            刷新
          </a-button>
          <a-button type="primary" @click="handleAddUser()">
            <template #icon>
              <PlusOutlined />
            </template>
            添加用户
          </a-button>
        </div>
      </a-form>
    </div>
    <el-table
      :data="tableModel.tableData"
      v-loading="tableModel.loading"
      border
    >
      <el-table-column prop="createAt" label="创建时间" width="300" />
      <el-table-column prop="username" label="用户账号" min-width="200"/>
      <el-table-column prop="realName" label="用户名称" min-width="200"/>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button link size="small" @click="handleEdit(scope.row)" icon="Edit"> 修改</el-button>
          <el-button
            link
            size="small"
            @click="handleDelete(scope.row)"
            icon="Delete"
            style="color: #f56c6c"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <UserUpdatePasswordModal ref="userUpdatePasswordModalRef"/>
    <UserModal ref="userModalRef"/>
  </el-card>
</template>

<script setup>
import { userUrl } from '@/api/api'
import { postAction } from '@/request/request'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'
import { API_BASE_URL } from '@/config'
import { ReloadOutlined,SearchOutlined,PlusOutlined } from '@ant-design/icons-vue'
import UserUpdatePasswordModal from '@/components/admin/modules/UserUpdatePasswordModal.vue'
import UserModal from '@/components/admin/modules/UserModal.vue'

onMounted(() => {
  getUserList()
})

const url = {
  list: userUrl.list,
  delete: userUrl.delete,
}

const queryParam = reactive({
  username: ''
})

const tableModel = reactive({
  dataSource: [],
  loading: false
})
const getUserList = () => {
  tableModel.loading = true
  postAction(url.list, { username: queryParam.username })
    .then(response => {
      if (response.code !== 200) {
        ElMessage.error({
          message: response.message,
          type: 'error',
          duration: 3000
        })
      } else {
        // 过滤掉管理员
        tableModel.tableData = response.data.filter(item => item.idType !== 0)
      }
    })
    .finally(() => {
      tableModel.loading = false
    })
}

const searchReset = () => {
  queryParam.username = ''
  getUserList()
}


const userModalRef = ref(null)

const handleAddUser = () => {
  userModalRef.value.show()
  userModalRef.value.isAdd = true
  getUserList()
}

const handleEdit = row => {
  userModalRef.value.show()
  userModalRef.value.isAdd = false
  userModalRef.value.form.username = row.username
  userModalRef.value.form.realName = row.realName
  getUserList()
}

const handleDelete = async row => {
  try {
    await ElMessageBox.confirm(`确定要删除用户 "${row.id}" 吗? 此操作不可恢复!`, '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      center: true
    })

    const loading = ElLoading.service({
      lock: true,
      text: '正在删除用户...',
      background: 'rgba(0, 0, 0, 0.7)'
    })

    try {
      const response = await fetch(`${API_BASE_URL}/delete_user`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          delete_id: row.id
        })
      })

      if (!response.ok) throw new Error('网络响应失败')

      const data = await response.json()
      if (data.message === '删除成功') {
        ElMessage.success('用户删除成功')
        fetchUserList()
      } else {
        ElMessage.error('用户删除失败')
      }
    } catch (error) {
      ElMessage.error('用户删除失败: ' + error.message)
    } finally {
      loading.close()
    }
  } catch (cancel) {
    // 用户点击了取消
  }
}

defineExpose({
  getUserList
})
</script>

<style scoped></style>
